package com.herui.sdyu_lib.base;

import android.content.Context;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;


import com.herui.sdyu_lib.base.fragment.Fragmentation;
import com.herui.sdyu_lib.base.fragment.helper.FragmentationNullException;
import com.herui.sdyu_lib.utils.LogUtils;
import com.herui.sdyu_lib.utils.ToastUtil;

import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentTransaction;

public abstract class BaseFragment extends Fragment {

    public String TAG = "BaseFragment";

    public boolean debug = true;

    protected BaseActivity baseActivity;
    protected Fragmentation fragmentation;

    private ViewGroup rootView = null;   // 缓存Fragment view
    protected boolean isInitUi;    // 已经初始化view
    protected boolean isCreate;

    protected long recordTime;

    public BaseFragment() {
        TAG = getClass().getName();
    }

    protected OnFragmentInteractionListener listener;

    public void setListener(OnFragmentInteractionListener listener) {
        this.listener = listener;
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        if (debug)
            LogUtils.d(TAG + " onAttach");
        baseActivity = (BaseActivity) context;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        isCreate = false;

        if (debug)
            LogUtils.d(TAG + " onCreate");
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);

        fragmentation = baseActivity.getFragmentation();
    }

    @Override
    public View onCreateView(LayoutInflater inflater,
                             ViewGroup container, Bundle savedInstanceState) {

        if (debug)
            LogUtils.i(TAG + " onCreateView");
        if (rootView == null) {
            rootView = (ViewGroup) inflater.inflate(getLayout(), container, false);
            if (getStf() != -1) {
                inflater.inflate(getStf(), rootView, true);
            }
        }

        isInitUi = false;
        isCreate = true;
        return rootView;
    }

    protected void showStf(){
        getStfView().setVisibility(View.VISIBLE);
        getContantView().setVisibility(View.GONE);
    }

    protected void hideStf(){
        getStfView().setVisibility(View.GONE);
        getContantView().setVisibility(View.VISIBLE);
    }

    @Override
    public void onResume() {
        super.onResume();

        if (debug)
            LogUtils.d(TAG + " onResume");
        if (!isInitUi)
            initParam();
        isInitUi = true;
    }

    protected void setStatusView(View statusView, int color) {
        int resourceId = baseActivity.getResources().getIdentifier("status_bar_height", "dimen",
                "android");
        int statusBarHeight = baseActivity.getResources().getDimensionPixelSize(resourceId);
        ViewGroup.LayoutParams layoutParams = statusView.getLayoutParams();
        layoutParams.height = statusBarHeight;
        statusView.setLayoutParams(layoutParams);
        statusView.setBackgroundColor(color);
    }

    @Override
    public void onPause() {
        LogUtils.d(TAG + " onPause");
        super.onPause();
    }

    @Override
    public void onDestroyView() {
        if (debug)
            LogUtils.d(TAG + " onDestroyView");
        super.onDestroyView();
    }

    @Override
    public void onDestroy() {
        if (debug)
            LogUtils.d(TAG + " onDestroy");
        super.onDestroy();
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        if (getChildFragmentManager().getFragments() != null) {
            for (Fragment fragment : getChildFragmentManager().getFragments()) {
                if (fragment != null) {
                    fragment.onHiddenChanged(hidden);
                }
            }
        }

        if (hidden) {
            onHidden();
            LogUtils.i(TAG + " 隐藏");
        } else {
            onShow();
            LogUtils.i(TAG + " 显示");
        }
    }

    /**
     * fragment 返回时是否需要刷新UI
     *
     * @return
     */
    public boolean returnRefresh() {
        return true;
    }

    /**
     * 显示
     */
    public void onShow() {

    }

    /**
     * 隐藏 不可见
     */
    protected void onHidden() {
    }

    /**
     * 按下返回键触发
     *
     * @return
     */
    public boolean onBackPressedSupport() {
        LogUtils.i("onBackPressed:" + getClass().getName());
        BaseFragment fragment = getTopChildFragment();
        if (fragment != null) {
            return fragment.onBackPressedSupport();
        } else {
            return false;
        }
    }

    public void removeSelf(FragmentDirectionAnim anim) {

        if (getParentFragment() != null) {
            FragmentTransaction ft = getParentFragment().getChildFragmentManager()
                    .beginTransaction();
            if (anim != null)
                ft.setCustomAnimations(anim.enterAnim, anim.exitAnim, anim.popEnter, anim.popExit);
            else
                ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_CLOSE);
            ft.remove(this).commitAllowingStateLoss();
            getParentFragment().getChildFragmentManager().popBackStack();
        } else {
            fragmentation.remove(this);
        }
    }

    /**
     * 添加一个fragment
     *
     * @param toFragment
     */
    public void add(BaseFragment toFragment, FragmentDirectionAnim anim) {
        if (System.currentTimeMillis() - recordTime > 500) {
            fragmentation.add(this, toFragment, anim);
            recordTime = System.currentTimeMillis();
        }
    }

    public void addWithFinish(BaseFragment to, FragmentDirectionAnim anim) {
        if (fragmentation == null) {
            throw new FragmentationNullException("startWithFinish()");
        }
        fragmentation.addWithFinish(this, to, anim);
    }

    /**
     * 出栈到目标fragment
     *
     * @param fragmentClass 目标fragment
     * @param includeSelf   是否包含该fragment
     */
    public void popTo(Class<?> fragmentClass, boolean includeSelf) {
        fragmentation.popTo(fragmentClass, includeSelf, getFragmentManager());
    }


    @Deprecated
    public void replaceFragment(int childContainer, Fragment childFragment, String TAG, boolean
            addToBack) {
        replaceChildFragment(childContainer, childFragment, addToBack, null);
    }

    /**
     * 获取父亲fragment
     *
     * @return
     */
    public BaseFragment getMyParentFragment() {
        return (BaseFragment) super.getParentFragment();
    }


    /**
     * 替换子Fragment
     *
     * @param childContainer
     * @param childFragment
     * @param addToBack
     */
    public void replaceChildFragment(int childContainer, Fragment childFragment, boolean
            addToBack, FragmentDirectionAnim anim) {
        FragmentTransaction ft = getChildFragmentManager().beginTransaction();
        if (anim != null)
            ft.setCustomAnimations(anim.enterAnim, anim.exitAnim);
        else
            ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
        ft.replace(childContainer, childFragment, childFragment.getClass().getName())
                .show(childFragment);
        if (addToBack) {
            ft.addToBackStack(childFragment.getClass().getName());
        }
        ft.commitAllowingStateLoss();
    }

    /**
     * 添加fragment
     *
     * @param childContainer
     * @param childFragment
     * @param addToBack
     */
    public void addChildFragment(int childContainer, Fragment childFragment, boolean
            addToBack, FragmentDirectionAnim anim) {

        if (childFragment.isVisible())
            return;

        FragmentTransaction ft = getChildFragmentManager().beginTransaction();
        if (anim != null)
            ft.setCustomAnimations(anim.enterAnim, anim.exitAnim);
        else
            ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);

        Fragment topChildFragment = getTopChildFragment();
        if (topChildFragment != null) {
            if (debug)
                LogUtils.i("addChildFragment hide top: " + topChildFragment.getClass().getName());
            ft.hide(topChildFragment);
        } else if (debug)
            LogUtils.i("addChildFragment no topfragment: ");

        if (!childFragment.isAdded())
            ft.add(childContainer, childFragment, childFragment.getClass().getName())
                    .show(childFragment);
        else
            ft.show(childFragment);
        if (addToBack) {
            ft.addToBackStack(childFragment.getClass().getName());
        }
        ft.commitAllowingStateLoss();
    }

    /**
     * 添加fragment 隐藏老的fragment 保留栈
     *
     * @param constantID
     * @param from
     * @param to
     */
    public void switchBrotherChildFragment(int constantID, BaseFragment from, BaseFragment to,
                                           FragmentDirectionAnim anim) {

        if (to.isVisible())
            return;
        FragmentTransaction ft = getChildFragmentManager().beginTransaction();
        if (anim != null)
            ft.setCustomAnimations(anim.enterAnim,
                    anim.exitAnim);
        else
            ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);

        if (from != null)
            ft.hide(from);
        if (!to.isAdded()) {
            ft.add(constantID, to, to.TAG).show(to).commitAllowingStateLoss();
        } else {
            ft.show(to).commitAllowingStateLoss();
        }
    }

    /**
     * 替换 兄弟Fragment
     *
     * @param brotherContainer
     * @param brotherFragment
     * @param addToBack
     */
    public void replaceBrotherFragment(int brotherContainer, BaseFragment brotherFragment,
                                       boolean addToBack, FragmentDirectionAnim anim) {
        FragmentTransaction ft = getFragmentManager().beginTransaction();
        if (anim != null)
            ft.setCustomAnimations(anim.enterAnim,
                    anim.exitAnim);
        else
            ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
        ft.replace(brotherContainer, brotherFragment, brotherFragment.getClass().getName())
                .show(brotherFragment);
        if (addToBack) {
            ft.addToBackStack(brotherFragment.getClass().getName());
        }
        ft.commitAllowingStateLoss();
    }

    /**
     * 得到位于栈顶的Fragment
     *
     * @return
     */
    public BaseFragment getTopFragment() {
        if (fragmentation == null) {
            throw new FragmentationNullException("getTopFragment()");
        }
        return fragmentation.getTopFragment(getFragmentManager());
    }

    /**
     * 得到位于栈顶的子Fragment
     *
     * @return
     */
    public BaseFragment getTopChildFragment() {
        if (fragmentation == null) {
            throw new FragmentationNullException("getTopFragment()");
        }
        return fragmentation.getTopFragment(getChildFragmentManager());
    }

    @Deprecated
    public void toast(String message) {
        ToastUtil.showMessage(message);
    }

    public abstract int getLayout();

    public abstract void initParam();

    /**
     * 获取状态覆盖布局页面
     *
     * @return
     */
    public int getStf() {
        return -1;
    }

    public View getStfView(){
        return null;
    }

    public View getContantView(){
        return null;
    }
}
